package com.qf.java2201.web;

import com.qf.java2201.dao.UserDao;
import com.qf.java2201.dao.impl.UserDaoImpl;
import com.qf.java2201.pojo.HUser;
import com.qf.java2201.service.UserService;
import com.qf.java2201.service.impl.UserServiceImpl;
import com.qf.java2201.utils.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @date 2022/4/6
 * @desc
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String uname = req.getParameter("uname");
        String upwd = req.getParameter("upwd");
        String remember = req.getParameter("remember");

        UserService userService = new UserServiceImpl();

        HUser huser = new HUser();

        huser.setUname(uname);

        huser.setUpwd(MD5Util.encodePwdByMD5(upwd));

        HttpSession session = req.getSession();

        HUser result = userService.login(huser);

        // 登录成功  跳转到 index.jsp
        if (result != null) {
            if (remember != null) {
                Cookie cookie = new Cookie("remember", result.getUname() + "-" + upwd);

                cookie.setMaxAge(Integer.parseInt(remember));

                resp.addCookie(cookie);
            }
            System.out.println("登录成功");
            session.setAttribute("u", result);
            resp.sendRedirect(req.getContextPath() + "/index.jsp");

        } else{
            System.out.println("登录失败");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);

        }

        // 登陆失败   跳转到 login.jsp


    }
}
